package com.sc.VenusQueryBeta.ui.fragments.vip;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.hengjun.kingstar.sdk.base.BasePresenter;
import com.hengjun.kingstar.sdk.base.fragment.BaseMVPCompatFragment;
import com.hengjun.kingstar.sdk.utils.APKVersionCodeUtils;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.hengjun.kingstar.sdk.utils.ToastUtils;
import com.sc.VenusQueryBeta.R;
import com.sc.VenusQueryBeta.adapter.UpdateServiceAdapter;
import com.sc.VenusQueryBeta.adapter.VerSionInfoAdapter;
import com.sc.VenusQueryBeta.contract.vip.VipRootContract;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.AboutVGSBean;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.presenter.vip.VipRootPresenter;
import com.sc.VenusQueryBeta.ui.fragments.login.LoginFragment;
import com.sc.VenusQueryBeta.ui.fragments.vip.child.VipUserFragment;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import butterknife.BindView;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;

/**
 * Created by SC-02 on 2018/9/19.
 * 这个是每个fragment中的根fragment 要继承BaseCompatFragment  即Activity内的第一个Fragment 或 Fragment内的第一个子Fragment
 * 在根fragment里面可以加载子fragment
 * VIP fragment
 */

public class VipRootFragment extends BaseMVPCompatFragment<VipRootContract.VipRootPresenter> implements VipRootContract.IVipRootView {

    @BindView(R.id.fl_container)
    FrameLayout flContainer;

    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;

    private Dialog mDownloadDialog;
    private ProgressBar mProgress;
    private TextView schedule;
    private boolean cancelUpdate = false;
    private VipRootFragment.downloadApkThread downloadApkThread;
    private PopupWindow popupWindow;
    private TextView tv_versionName;
    private Button btn_update;
    private Button btn_update_cancel;
    private VerSionInfoAdapter verSionInfoAdapter;
    private RecyclerView rv_update_info;
    private AlertView mCallView;
    private View contentView;
    private int item;
    private UsersLoginBean loginBean;
    private CompositeDisposable compositeDisposable;
    private WebView webView;
    private TextView mpercentage;

    /**
     * 实例化
     *
     * @return
     */
    public static VipRootFragment newInstance() {
        Bundle bundle = new Bundle();
        VipRootFragment vipRootFragment = new VipRootFragment();
        vipRootFragment.setArguments(bundle);
        return vipRootFragment;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        LogUtil.e("onLazyInitView");
        UsersLoginBean loginBean = SpUtils.getObject(mActivity, UsersLoginBean.class);
        if (loginBean != null && !loginBean.getId().equals("")) {//已登錄
            long l = System.currentTimeMillis();
            long l1 = (long) 10000000000.0;
            showProgressDialog(getString(R.string.now_check));
            for (int i = 0; i < 10; i++) {
                item = (int) ((Math.random() * 9 + i) * 1000000000);
            }
            LogUtils.e("生成的随机数" + item);
            mPresenter.aboutVGS(l % l1);

        }
    }


    /**
     * 写布局
     *
     * @return
     */
    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }

    /**
     * 初始化这个布局的UI
     *
     * @param view               view
     * @param savedInstanceState savedInstanceState
     */
    @Override
    public void initUI(View view, @Nullable Bundle savedInstanceState) {
        LogUtils.e("VipRootFragment initUI");
        loginBean = SpUtils.getObject(MyApplication.getContext(), UsersLoginBean.class);
        if (loginBean != null && !loginBean.getId().equals("")) {//已登錄
            LogUtils.e("已登錄111111");
            //当VipUserFragment为空时
            if (findChildFragment(VipUserFragment.class) == null) {
                LogUtils.e("已登錄");
                loadRootFragment(R.id.fl_container, VipUserFragment.newInstance(), true, true);
            } else {
                LogUtils.e("VipUserFragment = null");
            }
        } else {//未登錄
            LogUtils.e("未登錄1");
            if (findChildFragment(LoginFragment.class) == null) {
                LogUtils.e("未登錄");
                loadRootFragment(R.id.fl_container, LoginFragment.newInstance(), false, true);
            } else {
                LogUtils.e("LoginFragment = null");
            }
        }
//        if (loginBean != null && !loginBean.getId().equals("")) {//已登錄
//            long l = System.currentTimeMillis();
//            long l1 =  (long)10000000000.0;
//            showProgressDialog("正在检查");
//            for (int i = 0; i < 10; i++) {
//                item = (int) ((Math.random() * 9 + i) * 1000000000);
//            }
//            LogUtils.e("生成的随机数" + item);
//            mPresenter.aboutVGS(l% l1);
//        }
        LogUtils.e("initUI");

    }

    /**
     * 弹出窗口
     *
     * @param aboutVGSBean
     */
    @SuppressLint("WrongConstant")
    private void inputOtherPwdWindow(final AboutVGSBean aboutVGSBean) {
        contentView = LayoutInflater.from(mActivity).inflate(R.layout.custom_version_update, null);
        if (popupWindow == null) {
            popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        }
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
        lp.alpha = 0.5f;
        mActivity.getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                lp.alpha = 1f;
                mActivity.getWindow().setAttributes(lp);
                if (webView != null) {
                    webView.clearCache(true);
                }
            }
        });
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true); //设置点击menu以外其他地方以及返回键退出
        popupWindow.setOutsideTouchable(true);   //设置触摸外面时消失
        popupWindow.getContentView().setFocusableInTouchMode(true);
        popupWindow.getContentView().setFocusable(true);
        // 设置弹出窗体的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable(MyApplication.app.getResources(), (Bitmap) null));
        ColorDrawable cd = new ColorDrawable();
        popupWindow.setBackgroundDrawable(cd);
        //这句话，让pop覆盖在输入法上面
        popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);//设置弹出动画

//
        tv_versionName = contentView.findViewById(R.id.tv_versionName);//版本名稱
        tv_versionName.setText(aboutVGSBean.getVer());
        webView = contentView.findViewById(R.id.webView);//版本名稱
        WebSettings settings = webView.getSettings();
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//设置wenview不缓存数据
        //更新信息
        rv_update_info = contentView.findViewById(R.id.rv_update_info);
        rv_update_info.setLayoutManager(new LinearLayoutManager(mActivity));
        rv_update_info.setAdapter(new UpdateServiceAdapter(R.layout.layout_version_item, aboutVGSBean.getList()));
        btn_update = contentView.findViewById(R.id.btn_update);//更新

        btn_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDownloadDialog(aboutVGSBean.getUrl());
                popupWindow.dismiss();

            }
        });

        btn_update_cancel = contentView.findViewById(R.id.btn_update_cancel);//取消更新

        btn_update_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        // 5 在底部显示
        popupWindow.showAtLocation(contentView.findViewById(R.id.rl_custom),
                Gravity.CENTER, 0, 0);
        webView.loadUrl("http://home.myvip18.com:8080/UpdateWizardServer/sanchuanAndroidApp/VenusQueryBeta/update/updateReadMe.html");

    }


    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog(String url) {
        // 构造软件下载对话框
        mDownloadDialog = new Dialog(mActivity, R.style.MyDialogStyle);
        mDownloadDialog.setContentView(R.layout.download_dialog);
        mProgress = (ProgressBar) mDownloadDialog.findViewById(R.id.progressBar1);
        Button exit = (Button) mDownloadDialog.findViewById(R.id.button1);
        mpercentage = mDownloadDialog.findViewById(R.id.tv_percentage);
        exit.setOnClickListener(new View.OnClickListener() {//点击进度条取消更新

            @Override
            public void onClick(View v) {
                mDownloadDialog.dismiss();
                cancelUpdate = true;
            }
        });
        mDownloadDialog.show();
        // 下載文件
        downloadApk(url);
    }

    /**
     * 下载apk文件
     *
     * @param url
     */
    private void downloadApk(String url) {
        // 启动新线程下载软件
//        new downloadApkThread(url).start();
        requestPermissions(url);
    }

    private void requestPermissions(final String url) {
        RxPermissions rxPermission = new RxPermissions(mActivity);
        //请求权限全部结果
        rxPermission.request(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (!granted) {
                            ToastUtils.showToast(getString(R.string.app_not_jurisdiction));
                            // 取消下载对话框显示
                            mDownloadDialog.dismiss();
                            popupWindow.dismiss();
                        } else {
                            // 启动新线程下载软件
                            downloadApkThread = new downloadApkThread("http://home.myvip18.com:8080/UpdateWizardServer/sanchuanAndroidApp/VenusQueryBeta/update/VenusQueryBeta.apk");
                            downloadApkThread.start();
                        }

                    }
                });
    }

    @NonNull
    @Override
    public BasePresenter initPresenter() {
        return VipRootPresenter.newInstance();
    }

    @Override
    public void showAboutVGSDataSuccess(AboutVGSBean aboutVGSBean) {
        hideProgressDialog();
        //    LogUtils.e("后台参数" + aboutSKBean.getTotalByte() + "     " + aboutSKBean.getUrl() + "      " + aboutSKBean.getVer() + "   size=  " + AboutSKBean.list.get(0));
        if (APKVersionCodeUtils.getVerName(mActivity).equals(aboutVGSBean.getVer())) {//当前版本一样

        } else {
//          update(aboutSKBean.getVer(),aboutSKBean);
            LogUtil.e("onceonce");
            inputOtherPwdWindow(aboutVGSBean);
        }
    }

    @Override
    public void showNetworkError(Throwable throwable) {
        LogUtils.e("error" + throwable.getMessage());
        hideProgressDialog();
    }

    /**
     * 下载文件线程  需要动态权限
     */
    public class downloadApkThread extends Thread {
        private String murl;

        public downloadApkThread(String url) {
            this.murl = url;
        }

        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory()
                            + "/";
                    mSavePath = sdpath + "SKQUERY";

                    URL url = new URL(murl);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "VenusQueryBeta.apk"+System.currentTimeMillis());
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        LogUtils.e("progress==" + progress);
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 101);
                        LogUtils.e("progress==" + progress);
                        // 更新进度
                        mHandler.sendEmptyMessage(1);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(2);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);
                    {
                        LogUtils.e("MalformedURLExgdgdgdgdgdg5498654189ception==");
                    }
                    fos.close();
                    is.close();
                } else {
                    LogUtils.e("MalformedURLExgdgdgdgdgdg5498654189ception==");
                }
            } catch (MalformedURLException e) {
                LogUtils.e("MalformedURLException==" + e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                LogUtils.e("IOException==" + e.getMessage());
                e.printStackTrace();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    }

    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, "VenusQueryBeta.apk");
        LogUtils.e("mSavePath===" + mSavePath);
        if (apkfile.exists()) {
            Intent intent = new Intent();
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri;
            if (Build.VERSION.SDK_INT >= 24) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//加这几话
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                LogUtils.e(apkfile.toString());
                uri = FileProvider.getUriForFile(mContext, "com.sc.VenusQueryBeta.fileProvider", apkfile);
            } else {
                uri = Uri.fromFile(apkfile);
            }
            intent.setDataAndType(uri,
                    "application/vnd.android.package-archive");
            mActivity.startActivity(intent);
        } else {
            mHandler.sendEmptyMessage(3);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case 1:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    mpercentage.setText(getString(R.string.down_progress) + String.valueOf(progress) + "%");
                    break;
                case 2:
                    // 安装文件
                    installApk();
                    break;
                case 3:
                    Toast.makeText(mActivity, R.string.soft_update_noIn,
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            webView.clearCache(true);
        }
    }
}
